<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
/**
 * 科学计算法多值的计算
 * 加bcadd($a, $b, 4)（留4位小数）
 * 减bcsub($a, $b, 4)
 * 乘bcmul($a, $b, 4)
 * 除bcdiv($a, $b, 4)
 * 取余bcmod($a, $b)
 * @param array $num_arr 数字数组
 * @param string $method +-*\/%
 * @param number $scale 保留几位小数
 */
function calculate($num_arr,$method='+',$scale=2){
	if(!is_array($num_arr)||empty($num_arr)){
		return 0;
	}
	switch ($method){
		case '+':
			$func = 'bcadd';
			break;
		case '-':
			$func = 'bcsub';
			break;
		case '*':
			$func = 'bcmul';
			break;
		case '/':
			$func = 'bcdiv';
			break;
		case '%':
			$func = 'bcmod';
			$scale = -1;
			break;
		default:
			return false;
	}
	$i = 0;
	$reNum = 0;
	foreach ($num_arr as $v){
		if(!is_numeric($v)){
			$v = 0;
		}
		if($i==0){
			$reNum = $v;
		}else{
			if($scale==-1){//取余
				$reNum = $func($reNum,$v);
			}else{
				$reNum = $func($reNum,$v,$scale);
			}

		}
		$i++;
	}
	return $reNum;
}